#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <functional>
#include <cstdio>
static const int t_num = 5; // 抢票线程数

int tickets = 1000; // 票数


pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *threadRoutine(void *args)
{
    char *name = static_cast<char *>(args);

    while (true)
    {
        // 票数大于0, 抢票
        pthread_mutex_lock(&mutex);
        if (tickets > 0)
        {
            // 模拟抢票花费的时间
            usleep(1000);
            std::cout << name << " get ticket number: " << tickets-- << std::endl;
            pthread_mutex_unlock(&mutex);
        }
        // 票数小于等于0, 退出
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
    }

    return nullptr;
}

int main()
{
    // 创建抢票的线程
    pthread_t tids[t_num];
    for (int i = 0; i < t_num; i++)
    {
        // 给每个线程一个名字
        char *name = new char[64];
        snprintf(name, 64, "thread-%d", i + 1);
        pthread_create(tids + i, nullptr, threadRoutine, name);
    }

    // 等待所有线程
    for (int i = 0; i < t_num; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    return 0;
}
